package com.wymobilearchitecture.study.thread.security;

import com.example.w_library.log.WLog;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示 多个线程 打印纸张(公平锁和非公平锁)
 */
public class ReentrantLockTest02 {

    public ReentrantLockTest02(){

        final ReentrantLockTask task = new ReentrantLockTask();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                task.print();
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
    }


    static class ReentrantLockTask{
        ReentrantLock lock = new ReentrantLock();

        void print(){
            String name = Thread.currentThread().getName();
            try{
                lock.lock();
                WLog.e(name + " 第一次打印");
                Thread.sleep(1000);
                WLog.e(name + " 第二次打印");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
